package com.example.springbootstartermqttprovider.utils;

import cn.hutool.json.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.StringJoiner;

public class HikCloudOAuthTokenExample {
 
    public static void main(String[] args) {
        OAuthTokenResponse accessToken = HikCloudOAuthTokenExample.getAccessToken();
        System.out.println("accessToken"+ cn.hutool.json.JSONUtil.toJsonStr(accessToken));
        AuthorizationTokenCON authorizationToken = HikCloudOAuthTokenExample.getAuthorizationToken(accessToken.getAccess_token());
        System.out.println("authorizationToken"+ cn.hutool.json.JSONUtil.toJsonStr(authorizationToken));
    }


    public static OAuthTokenResponse getAccessToken() {
        try {
            // 构建请求参数
            StringJoiner formParams = new StringJoiner("&");
            formParams.add(URLEncoder.encode("client_id", String.valueOf(StandardCharsets.UTF_8)) + "="
                    + URLEncoder.encode("49fec86e5d50475abd85ad84ebb7052a", String.valueOf(StandardCharsets.UTF_8)));
            formParams.add(URLEncoder.encode("client_secret", String.valueOf(StandardCharsets.UTF_8)) + "="
                    + URLEncoder.encode("e1a3a14d553143468a9e29ec7477de46", String.valueOf(StandardCharsets.UTF_8)));
            formParams.add(URLEncoder.encode("grant_type", String.valueOf(StandardCharsets.UTF_8)) + "="
                    + URLEncoder.encode("client_credentials", String.valueOf(StandardCharsets.UTF_8)));
            formParams.add(URLEncoder.encode("scope", String.valueOf(StandardCharsets.UTF_8)) + "="
                    + URLEncoder.encode("app", String.valueOf(StandardCharsets.UTF_8)));

            // 创建 URL 对象
            URL url = new URL("https://api2.hik-cloud.com/oauth/token");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 发送请求参数
            try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
                outputStream.writeBytes(formParams.toString());
                outputStream.flush();
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    OAuthTokenResponse response11 = objectMapper.readValue(response.toString(), OAuthTokenResponse.class);
                    return response11;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static AuthorizationTokenCON getAuthorizationToken(String authorizationCode) {
        try {
            // 创建 URL 对象
            URL url = new URL("https://api2.hik-cloud.com/v1/ezviz/account/info");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为 GET
            connection.setRequestMethod("GET");
            // 添加请求头 Authorization
            String authorizationHeader = "Bearer "+authorizationCode;
            connection.setRequestProperty("Authorization", authorizationHeader);

            // 读取响应代码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 如果响应码是 200 (HTTP_OK)，则读取响应体
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        AuthorizationTokenCON response11 = objectMapper.readValue(response.toString(), AuthorizationTokenCON.class);
                        return response11;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                System.out.println("GET request failed.");
            }
            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}